package com.chesnutconsulting.otbasket.controller;



import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.chesnutconsulting.otbasket.image.finder.artesia.OtMetadataFinder;
import com.chesnutconsulting.otbasket.image.watermark.WatermarkedImageCreator;
import com.chesnutconsulting.otbasket.mail.Emailer;
import com.chesnutconsulting.otbasket.mail.ImageInfoAtom;
import com.chesnutconsulting.otbasket.util.FileUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.artesia.asset.AssetIdentifier;
import com.chesnutconsulting.otbasket.image.finder.artesia.OtImageFinder;

@Controller
@RequestMapping("/displayEmailPrintForm")
public class EmailPrintDisplayController {


//	@Inject
	OtImageFinder imageFinder;


	
	@RequestMapping(method = RequestMethod.GET)
	public String printWelcome(ModelMap model, HttpServletRequest request) {
		String[] assetIds = request.getParameterValues("ids");

		List<EmailPrintData> emailPrintDataList = new ArrayList<EmailPrintData>();
		for (int i = 0; i < assetIds.length; i++) {
			try {
				AssetIdentifier assetId = new AssetIdentifier(assetIds[i]);

				EmailPrintData epd = new EmailPrintData();
				epd.setAssetId(assetId.asString());
				epd.setImageUrl(imageFinder.getScreenResImageUrl(assetId
						.asString()));
				epd.setMetadataMap(imageFinder
						.getScalarMetadataForAsset(assetId));

				emailPrintDataList.add(epd);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		model.addAttribute("emailPrintDataList", emailPrintDataList);
		return "displayEmailPrint";
	}
/*	
	@RequestMapping(method = RequestMethod.GET)
	public @ResponseBody List<EmailPrintData> getAssetJson(HttpServletRequest request) {

		String[] assetIds = request.getParameterValues("ids");

		List<EmailPrintData> emailPrintDataList = new ArrayList<EmailPrintData>();
		for (int i = 0; i < assetIds.length; i++) {
			try {
				AssetIdentifier assetId = new AssetIdentifier(assetIds[i]);

				EmailPrintData epd = new EmailPrintData();
				epd.setAssetId(assetId.asString());
//				epd.setImageUrl(imageFinder.getScreenResImageUrl(assetId
//						.asString()));
//				epd.setMetadataMap(imageFinder
//						.getScalarMetadataForAsset(assetId));
//
				epd.setImageUrl("some image");
				Map<String, String> metadataMap = new HashMap<String, String>();
				metadataMap.put("a", "a");
				metadataMap.put("b", "b");
				metadataMap.put("c", "c");
				epd.setMetadataMap(metadataMap);
				
				emailPrintDataList.add(epd);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		return emailPrintDataList;
	}
*/
	public OtImageFinder getImageFinder() {
		return imageFinder;
	}

	public void setImageFinder(OtImageFinder imageFinder) {
		this.imageFinder = imageFinder;
	}
/*
    @RequestMapping(value = "/basket/email", method = RequestMethod.POST)
    public String emailBasket(@RequestBody BasketEmailInfo emailInfo) {
        boolean success = false;
        try {
            watermarkAndEmailAssets(emailInfo);
            success = true;
        } catch (Exception e) {
            LOGGER.error("Watermarking/Emailing operation failed.", e);
        }

        return (success) ? "displayEmailSent" : "displayEmailPrint";
    }

    void watermarkAndEmailAssets(BasketEmailInfo emailInfo) throws Exception {
        List<File> downloadedImageFiles = imageFinder.getImages(emailInfo.getAssetIds());
        String imageStorePath = watermarkedImageCreator.watermark(downloadedImageFiles);
        List<ImageInfoAtom> imageInfoAtoms = prepareImageInfoAtoms(imageStorePath, emailInfo);
        emailer.emailBasket(emailInfo.getToEmail(),
                            emailInfo.getSubject(),
                            emailInfo.getAdditionalMessage(),
                            imageInfoAtoms);
    }

    List<ImageInfoAtom> associatedMetadata(List<ImageInfoAtom> atoms) throws Exception {
        for(ImageInfoAtom atom : atoms) {
            AssetIdentifier teamsId = new AssetIdentifier(atom.getDerivedAssetId());
            Map<String, String> metadataWithIds = imageFinder.getScalarMetadataForAsset(teamsId);
            Map<String, String> metadataWithPrompts = transformFieldIdsToPrompt(metadataWithIds);
            atom.setMetadata(metadataWithPrompts);
        }

        return atoms;
    }

    List<ImageInfoAtom> prepareImageInfoAtoms(String imageStorePath, BasketEmailInfo emailInfo) throws Exception {
        List<File> watermarkedFiles = FileUtil.getFilesFromDir(imageStorePath, "jpg");
        List<ImageInfoAtom> imageInfoAtoms = Lists.newArrayList();
        for(File file : watermarkedFiles) {
            ImageInfoAtom atom = new ImageInfoAtom(file);
            String assetId = atom.getDerivedAssetId();
            atom.setComment(emailInfo.commentForAssetId(assetId));
            imageInfoAtoms.add(atom);
        }

        return associatedMetadata(imageInfoAtoms);
    }

    Map<String, String> transformFieldIdsToPrompt(Map<String, String> withIds) {
        Map<String, String> withPrompts = Maps.newHashMap();
        for(String fieldId : withIds.keySet()) {
            withPrompts.put(
                    metadataFinder.getPrompt(fieldId),
                    withIds.get(fieldId)
            );
        }

        return withPrompts;
    }
    */
}
